package com.algorithm.recursion;

/**
 * 递归二分查找
 * 时间复杂度O(logn)
 */
public class E03BinarySearch {
    public static int search(int[] a, int target) {
        int i = 0, j = a.length - 1;
        while (i <= j) {
            int m = (i + j) >>> 1;
            if (target == a[m]) {
                return m;
            } else if (target > a[m]) {
                i = m + 1;
            } else {
                j = m - 1;
            }
        }
        return -1;
    }

    public static int RecursionSearch(int[] a, int target) {
        return f(a, target, 0, a.length - 1);
    }

    private static int f(int[] a, int target, int i, int j) {
        if (i>j) {
            return -1;
        }
        int m = (i + j) >>> 1;
        if (target > a[m]) {
            return f(a, target, m + 1, j);
        } else if (target < a[m]) {
            return f(a, target, i, m - 1);
        } else {
            return m;
        }
    }


    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        System.out.println(search(a, 10));
        System.out.println(RecursionSearch(a, 10));
        System.out.println(search(a, 15));
        System.out.println(RecursionSearch(a, 15));
    }
}
